package org.rain.bee.boot;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.web.filter.OncePerRequestFilter;

//@EnableOAuth2Client
//@EnableOAuth2Sso
@EnableWebSecurity
@Configuration
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfigure extends WebSecurityConfigurerAdapter {

	
	
	@Autowired
    private UserDetailsService userService;


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        //校验用户
		auth.userDetailsService(userService).passwordEncoder( new BCryptPasswordEncoder()/*
																 * new PasswordEncoder() { //对密码进行加密
																 * 
																 * @Override public String encode(CharSequence charSequence) {
																 * System.out.println(charSequence.toString()); return
																 * DigestUtils.md5DigestAsHex(charSequence.toString().getBytes()); } //对密码进行判断匹配
																 * 
																 * @Override public boolean matches(CharSequence charSequence, String s) {
																 * String encode =
																 * DigestUtils.md5DigestAsHex(charSequence.toString().getBytes()); boolean res =
																 * s.equals( encode ); return res; } }
																 */ );

    }
	
	
	
	
	
	@Override
	public void configure(HttpSecurity http) throws Exception {
		/*
		 * http.antMatcher("/dashboard1/**").authorizeRequests().anyRequest().
		 * authenticated().and().csrf().csrfTokenRepository(csrfTokenRepository()).and()
		 * .addFilterAfter(csrfHeaderFilter(),
		 * CsrfFilter.class).logout().logoutUrl("/dashboard/logout").permitAll().
		 * logoutSuccessUrl("/").and().formLogin() .loginPage("/login")
		 * .defaultSuccessUrl("/user-page") .permitAll();
		 */

		http.authorizeRequests().antMatchers("/", "/actuator/**", "/dashboard/**", "index", "/login", "/login-error", "/401", "/css/**", "/js/**")
		.permitAll()
		.anyRequest()
		.authenticated()
		.and()
		.formLogin()
		.loginPage("/login")
		.failureUrl("/login-error")
		.and()
		.exceptionHandling()
		.accessDeniedPage("/401");
		
		http.logout().logoutSuccessUrl("/loginout");

	}

	private Filter csrfHeaderFilter() {
		return new OncePerRequestFilter() {
			@Override
			protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
					throws ServletException, IOException {
				CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
				if (csrf != null) {
					Cookie cookie = new Cookie("XSRF-TOKEN", csrf.getToken());
					cookie.setPath("/");
					response.addCookie(cookie);
				}
				filterChain.doFilter(request, response);
			}
		};
	}

	private CsrfTokenRepository csrfTokenRepository() {
		HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
		repository.setHeaderName("X-XSRF-TOKEN");
		return repository;
	}

	@Bean
	@Override
	public UserDetailsService userDetailsService() {

		UserDetails user = User.builder().username("user").password("user").roles("USER").build();

		return new InMemoryUserDetailsManager(user);
	}
	
	@Bean("BCryptPasswordEncoder")
	public BCryptPasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

}
